<template>
  <el-card shadow="never" class="box">
    <template #header>
      <span class="title" style="font-size: 28px; font-weight: 700;">看诊记录</span>
    </template>

    <!-- 1. 统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card done">
          <div class="stat-number">{{ todayDone }}</div>
          <div class="stat-label">今日已看诊（人）</div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card queue">
          <div class="stat-number">{{ queueNow }}</div>
          <div class="stat-label">当前排队（人）</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 2. 搜索 -->
    <el-form :inline="true" :model="search" class="search-area">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
            v-model="search.realName"
            placeholder="输入患者姓名搜索"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix><el-icon><Search /></el-icon></template>
          </el-input>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 3. 表格 -->
    <el-table :data="pageTable" stripe border>
      <el-table-column prop="index" label="编号" width="100" />
      <el-table-column prop="realName" label="患者姓名" />
      <el-table-column label="症状描述" min-width="240">
        <template #default="{ row }">
          <div v-if="row.present">{{ row.present }}</div>
          <div v-else-if="row.loading" class="loading-cell">
            <el-skeleton active />
          </div>
          <div v-else>
            <el-button 
              type="text" 
              size="small" 
              @click="fetchMedicalRecordAndShowDetail(row)"
            >
              查看症状
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.visitState)">{{ getStatusText(row.visitState) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="visitDate" label="日期" width="180" />
    </el-table>

    <!-- 4. 分页 -->
    <el-pagination
      v-model:current-page="page.current"
      :page-size="page.size"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handlePage"
      class="pagination"
    />
  </el-card>
  <!-- 详情弹窗 -->
  <el-dialog 
    v-model="detailVisible" 
    title="病历详情" 
    width="60%"
    :before-close="handleClose"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="症状描述">{{ currentRecord.present }}</el-descriptions-item>
      <el-descriptions-item label="治疗情况">{{ currentRecord.presentTreat }}</el-descriptions-item>
      <el-descriptions-item label="既往病史">{{ currentRecord.history }}</el-descriptions-item>
      <el-descriptions-item label="过敏史">{{ currentRecord.allergy }}</el-descriptions-item>
      <el-descriptions-item label="体格检查">{{ currentRecord.physique }}</el-descriptions-item>
      <el-descriptions-item label="处理建议">{{ currentRecord.proposal }}</el-descriptions-item>
      <el-descriptions-item label="注意事项">{{ currentRecord.careful }}</el-descriptions-item>
      <el-descriptions-item label="诊断结果">{{ currentRecord.diagnosis }}</el-descriptions-item>
      <el-descriptions-item label="治疗方案">{{ currentRecord.cure }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { registerApi } from '@/api'  // 复用患者查看页面的分页接口
import patientApi from '@/api/patient'

/* ---------- 数据 ---------- */
const tableData = ref([])
const search = reactive({ realName: '' })
const page = reactive({ current: 1, size: 5 })
const total = ref(0)

/* 今日统计 & 排队 */
const todayDone = ref(0)
const queueNow = computed(() => tableData.value.filter(i => i.visitState === 1).length)

/* ---------- 搜索 & 分页 ---------- */
const filterList = computed(() => {
  if (!search.realName) return tableData.value
  return tableData.value.filter(
    i => i.realName && i.realName.includes(search.realName)
  )
})

const pageTable = computed(() => {
  return filterList.value.map((item, index) => ({
    ...item,
    index: (page.current - 1) * page.size + index + 1
  }))
})

// 获取看诊记录列表（复用患者查看的分页接口）
async function fetchRecords() {
  const loading = ElLoading.service({ text: '加载中...' })
  try {
    const params = {
      pageNum: page.current,
      pageSize: page.size,
      ...(search.realName ? { realName: search.realName } : {})
    }
    
    const res = await registerApi.getByPage(params)  // 使用相同的分页接口
    tableData.value = res.list || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error(`获取看诊记录失败：${error.message || '未知错误'}`)
    console.error('获取看诊记录失败:', error)
  } finally {
    loading.close()
  }
}

// 获取今日统计数据
async function getTodayStatistics() {
  try {
    const res = await patientApi.getTodayStats()
    if (res.success && res.data) {
      todayDone.value = res.data.doneCount || 0
    } else {
      // 降级处理：从当前列表计算
      todayDone.value = tableData.value.filter(i => i.visitState === 2).length
    }
  } catch (error) {
    console.warn('获取统计数据失败，使用本地计算:', error)
    todayDone.value = tableData.value.filter(i => i.visitState === 2).length
  }
}

/* ---------- 操作 ---------- */
function handleSearch() {
  page.current = 1
  fetchRecords()
}

function handlePage(newPage) {
  page.current = newPage
  fetchRecords()
}

// 详情弹窗相关
const detailVisible = ref(false)
const currentRecord = ref({})

// 获取病历信息并显示详情弹窗
function fetchMedicalRecordAndShowDetail(row) {
  row.loading = true
  patientApi.getMedicalRecordByRegisterId(row.id)
    .then(response => {
      const records = response.data || []  // 接口直接返回病历数组
      console.log('病历数据:', records[0])
      
      // 检查是否有数据
      if (records.length > 0) {
        // 保存完整记录用于弹窗显示（取第一条）
        currentRecord.value = records[0]
        // 在表格中显示症状描述
        row.present = currentRecord.value.present || '无症状描述'
        // 显示弹窗
        detailVisible.value = true
      } else {
        ElMessage.warning('未找到病历信息')
        row.present = '无相关记录'
      }
    })
    .catch(error => {
      ElMessage.error('获取症状描述失败')
      console.error(error)
    })
    .finally(() => {
      row.loading = false
    })
}
// 关闭弹窗时的处理
function handleClose() {
  detailVisible.value = false
  // 可以在这里添加额外的清理逻辑
}

function getStatusText(state) {
  switch (state) {
    case 1: return '未诊断'
    case 2: return '诊毕'
    case 3: return '进行中'
    default: return '未知'
  }
}

function getStatusType(state) {
  switch (state) {
    case 1: return 'danger'
    case 2: return 'info'
    case 3: return 'success'
    default: return ''
  }
}

// 初始化加载数据
onMounted(async () => {
  await fetchRecords()
  await getTodayStatistics()
})
</script>

<style lang="scss" scoped>
.box {
  padding: 0 20px 20px 20px;
}
.stat-row {
  margin-bottom: 20px;
}
.stat-card {
  text-align: center;
  border-radius: 8px;
  &.done {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    color: #fff;
  }
  &.queue {
    background: linear-gradient(135deg, #409eff 0%, #5da8ff 100%);
    color: #fff;
  }
  .stat-number {
    font-size: 32px;
    font-weight: 700;
  }
  .stat-label {
    font-size: 14px;
    margin-top: 4px;
  }
}
.search-area {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
.loading-cell {
  width: 100%;
  padding: 4px 0;
}
</style>